package com.hydra.base.utils;

import cn.hutool.core.util.StrUtil;
import com.hydra.base.dto.auth.AuthUser;
import com.nimbusds.jose.JWSObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
import java.text.ParseException;
import java.util.Base64;
import java.util.Objects;

@Slf4j
public class RequestUtils {


    /**
     * 获取用户请求
     */
    public static HttpServletRequest getRequest() {
        return ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
    }

    /**
     * 获取登录认证的客户端ID
     * <p>
     * 兼容两种方式获取OAuth2客户端信息（client_id、client_secret）
     * 方式一：client_id、client_secret放在请求路径中
     * 方式二：放在请求头（Request Headers）中的Authorization字段，且经过加密，例如 Basic Y2xpZW50OnNlY3JldA== 明文等于 client:secret
     *
     * @return
     */
    public static String getClientId() {

        HttpServletRequest request = getRequest();

        // 从请求路径中获取
        String clientId = request.getParameter("client_id");
        if (StrUtil.isNotBlank(clientId)) {
            return clientId;
        }

        // 从请求头获取
        String basic = request.getHeader("Authorization");
        if (StrUtil.isNotBlank(basic) && basic.startsWith("Basic ")) {
            basic = basic.replace("Basic ", "");
            String basicPlainText = new String(Base64.getDecoder().decode(basic.getBytes(StandardCharsets.UTF_8)), StandardCharsets.UTF_8);
            clientId = basicPlainText.split(":")[0]; //client:secret
        }
        return clientId;
    }


    /**
     * 获取JWT Payload
     *
     * @return
     */
    public static String getJwtPayload() {
        HttpServletRequest request = getRequest();
        String payload = null;
        String authorization = request.getHeader("Authorization");
        if (StrUtil.isNotBlank(authorization) && StrUtil.startWithIgnoreCase(authorization, "Bearer ")) {
            authorization = StrUtil.replaceIgnoreCase(authorization, "Bearer ", "");
            try {
                payload = JWSObject.parse(authorization).getPayload().toString();
            } catch (ParseException e) {
                log.error(e.getMessage());
            }
        }
        return payload;
    }

    public static void main(String[] args) {
        try {
            String authorization = "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySW5mbyI6eyJjb2RlIjoiVUMwMDAwMDAxIiwidXNlcm5hbWUiOiJhZG1pbiIsImVtYWlsIjoiNjc3OTc0MjVAcXEuY29tIiwicGhvbmUiOiIxNTk4NjQyMzk4MiIsIm5hbWUiOiLotoXnuqfnrqHnkIblkZgiLCJzeXN0ZW1Db2RlIjpudWxsLCJyb2xlcyI6W3sicm9sZUNvZGUiOiJST0xFX1NVX0FETUlOIiwicm9sZU5hbWUiOiLotoXnuqfnrqHnkIblkZgifV19LCJleHAiOjE3MDI1MzY5NDIsImF1dGhvcml0aWVzIjpbIlJPTEVfU1VfQURNSU4iXSwianRpIjoiMDQwNTAwNGYtMjFkMC00NzQzLWJhZmItMWY3MjhjNTkwNmUyIiwiY2xpZW50X2lkIjoiV2ViIiwic2NvcGUiOlsiYWxsIl19.gGBUrmEzarsgTnYp_rsObGodL_WlDET-g3rBZ6iQSHbHL9YxKRzxEjmWyk9dbzgSBgU9a8LWXgTANvTwQWbSlc9JIVj9fO61f3zbIwXrcMP15bxcpXXGGsKbhmoMLbt8sl3gbeVd7tNtDccsdVatCGlVHGM85cQENds4z7L_lK9jOxKbs-ob2ip7pkHyG_eSUXUTztqAQgHtDOukwwpgRMTxIizdJDpH8qsFH99EEXEjrQEwCDyyvBKLeCIkkVRvoiR4dMvLM5-sfTBaYcjqpw4_bK1CNlh32zuZFBm5MWfiz6ZF1FqYvhw_bYCU4D8mDQkZVSFjWAjQJ0W3POVfOw";
            String payload = JWSObject.parse(authorization).getPayload().toString();
            System.out.println(payload);
        } catch (ParseException e) {
            log.error(e.getMessage());
        }
    }

    public static AuthUser getAuthUser(){
        String payload = getJwtPayload();
        if(StringUtils.isBlank(payload)){
            return null;
        }
        return JsonUtil.parseObject(payload).getObject("userInfo", AuthUser.class);
    }


}
